package com.css.apps.base.post.action;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.util.StringHelper;

import com.css.apps.base.org.model.SOrg;
import com.css.apps.base.user.model.SUser;
import com.css.db.query.QueryCache;
import com.css.ids.server.service.IdsService;
import com.css.util.ListUtil;
import com.css.util.Messages;
import com.css.webbase.webwork.action.UserAction;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class GetPostUser extends UserAction {

	private String postId;
	private String oldItems;
	
	@SuppressWarnings("unchecked")
	@Override
	protected String userGo() {
		if (StringHelper.isEmpty(postId)) {
			setMessage(Messages.getString("systemMsg.fieldEmpty"));
			return ERROR;
		}
		JSONArray res = new JSONArray();
		List<String> orgIdList = new QueryCache("select b.orgId from SOrgPost b where b.postId = :postId")
				.setParameter("postId", postId).list();
		Set<String> orgIds = new HashSet<>();
		for (String orgId : orgIdList) {
			getParent(orgId, orgIds);
		}
		List<SOrg> orgList = new QueryCache("from SOrg where uuid in (:orgIds)").setParameter("orgIds", orgIds).list();
		if (ListUtil.isLstNotEmpty(orgList)) {
			JSONObject one = null;
			for (SOrg org : orgList) {
				one = new JSONObject();
				one.put("id", org.getUuid());
				one.put("name", org.getName());
				one.put("pId", org.getParentId());
				one.put("type", "org");
				one.put("isParent", true);
				res.add(one);
			}
		}
		StringBuilder userHql = new StringBuilder("from SUser a where a.uuid in");
		userHql.append(" (select b.userId from SUserOrg b where b.orgId in (:orgIds))")
			.append(" and userType = '1' and openFlag = '1' and delFlag = '2'");
		List<SUser> userList = new QueryCache(userHql.toString())
				.setParameter("orgIds", orgIds).list();
		if (ListUtil.isLstNotEmpty(userList)) {
			JSONObject one = null;
			for (SUser user : userList) {
				one = new JSONObject();
				one.put("id", user.getUserId());
				one.put("name", user.getRealName());
				one.put("pId", user.getOrgId());
				one.put("type", "user");
				res.add(one);
			}
		}
		result = res.toString();
		return SUCCESS;
	}
	
	private void getParent(String parentId, Set<String> orgIds) {
		SOrg parent = QueryCache.get(SOrg.class, parentId);
		orgIds.add(parentId);
		if (IdsService.ORG_ORG_TYPE.equals(parent.getOrgType())) {
			return;
		} else {
			getParent(parent.getParentId(), orgIds);
		}
	}

	public String getPostId() {
		return postId;
	}

	public void setPostId(String postId) {
		this.postId = postId;
	}

	public String getOldItems() {
		return oldItems;
	}

	public void setOldItems(String oldItems) {
		this.oldItems = oldItems;
	}

}
